package broker

import (
	"fmt"
	"github.com/nats-io/nats.go"
	"honeyweb/conf"
	"honeyweb/log"
	"honeyweb/model"
	"time"
)
var defaultNC *nats.Conn
const (
	REQ_TIMEOUT = time.Second
)

//初始化
func ConnectNats(c *conf.NatsConf) *nats.Conn {
	natsUrl := fmt.Sprintf("nats://%s:%d",c.Host, c.Port)
	if c, err := nats.Connect(natsUrl, nats.UserInfo(c.User, c.Password)); err== nil {
		defaultNC = c
		log.S().Debugf("nats: %s connect success", c.ConnectedUrl())
		return c
	} else {
		panic(err)
	}
	return nil
}

//TODO 要做一个所有订阅消息的管理
func Subscribe(subject string, cb nats.MsgHandler) (*nats.Subscription, error){
	return defaultNC.Subscribe(subject, cb )
}

func UnSubscribe(sub *nats.Subscription) {
	sub.Unsubscribe()
}

func Request(subject string, data []byte) ([]byte, error) {
	msg , err := defaultNC.Request(subject, data, REQ_TIMEOUT)
	if err != nil {
		return nil, err
	}
	return msg.Data, nil
}

func PushMsg(subject string, msg interface{}) {
	data, err := model.Encode(msg)
	if err != nil {
		log.S().Errorf("push msg subject:%s encode msg:%+v err: %v", subject,msg, err)
	}
	err = defaultNC.Publish(subject, data)
	if err != nil {
		log.S().Infof("push subject:%s  msg:%+v err: %v", subject,msg, err)
	}
}



func PushAccountMsg(uid int, data []byte) error {
	subject := UserAgentEvent(uid)
	return defaultNC.Publish(subject, data)
}

func PushGroupAccountMsg(uids []int, data []byte) error {
	if len(uids) > 0 {
		for _, uid := range uids {
			if err := PushAccountMsg(uid, data); err != nil {
				return err
			}
		}
	}
	return nil
}

func PushAllAccountMsg(data []byte) error {
	return PushAccountMsg(ANY_UID, data)
}

